package game.leon.engine.data;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Excel中的数据
 * User: bianpeng
 * Date: 12-2-2
 */
public class ExcelData {
    private static final int MAX_ROW_NUM = 10000;
    private Logger logger = Logger.getLogger(getClass());

    private Workbook workbook;
    public ExcelData(Workbook workbook) {
        this.workbook = workbook;
    }
    public ExcelData(String path) {
        this.workbook = openWorkbook(path);
    }
    private Workbook openWorkbook(String path) {
        InputStream input = getClass().getResourceAsStream(path);
        try {
            XSSFWorkbook workbook = new XSSFWorkbook(input);
            return workbook;
        } catch (IOException e) {
            logger.error("", e);
        }
        return null;
    }
    //
    // 跳过第一行, 表头
    //
    public <T> List<T> getDataList(ExcelDataType<T> dataType, String sheetName) {
        return getDataList(dataType, sheetName, 1, MAX_ROW_NUM);
    }
    public <T> List<T> getDataList(ExcelDataType<T> dataType, String sheetName, int start, int stop) {
        Sheet sheet = workbook.getSheet(sheetName);
        if (sheet == null) return null;
        List<T> dataList = new ArrayList<T>();
        for(int rownum = start; rownum < stop; ++rownum) {
            Row row = sheet.getRow(rownum);
            // 结束条件判断
            if (row == null || row.getCell(0) == null) break;
            T data = dataType.make(row);
            dataList.add(data);
        }
        return dataList;
    }
    public <T> List<T> getDataList(Class<T> dataType, String sheetName) {
        return getDataList(new ExcelDataType<T>(dataType), sheetName);
    }
}
